package com.ycfmedical.bed.local;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.greendao.gen.DaoMaster;
import com.ycfmedical.bed.greendao.gen.DaoSession;

import android.content.Context;


/**
 * Created by Egoist on 2016/7/24.
 */
public class YcfDbHelper {

    private static YcfDbHelper sInstance;
    private static Context mContext;

    private static DaoMaster daoMaster;
    private static DaoSession daoSession;

    private YcfDbHelper() {
    }

    public static void init(Context context) {
        mContext = context;
        sInstance = new YcfDbHelper();
        // 注意：数据库连接属于 DaoMaster，所以多个 Session 指的是相同的数据库连接。
        DaoSession daoSession = getDaoSession(mContext);

    }

    public static YcfDbHelper getInstance() {
        return sInstance;
    }


    /**
     * 取得DaoMaster
     * @param context
     * @return
     */
    public static DaoMaster getDaoMaster(Context context) {
        if (daoMaster == null) {
            //通过 DaoMaster 的内部类 DevOpenHelper，你可以得到一个便利的 SQLiteOpenHelper 对象。
            DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,
                    Constants.DB_NAME, null);
            daoMaster = new DaoMaster(helper.getWritableDatabase());
        }
        return daoMaster;
    }

    /**
     * 取得DaoSession
     *
     * @param context
     * @return
     */
    public static DaoSession getDaoSession(Context context) {
        if (daoSession == null) {
            if (daoMaster == null) {
                //取得DaoMaster
                daoMaster = getDaoMaster(context);
            }
            //取得DaoSession
            daoSession = daoMaster.newSession();
        }
        return daoSession;
    }

}
